import Router from "koa-router"
import bodyParser from "koa-bodyparser"
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

export function useRouter(app,controller = 'controller'){
  let router = new Router()
  app.use(bodyParser())
  console.log(path.join(import.meta.url,'../../../')) 
  //打印控制器文件夹路径  file:///
  let fileName = path.join(import.meta.url,'../../../',controller)
  console.log(fs.existsSync(fileURLToPath(fileName))) 
  if(fs.existsSync(fileURLToPath(fileName))){
    // console.log(fs.readdirSync(fileURLToPath(fileName)))//读取文件夹里面的文件并返回一个数组
    let fileNameAll = fs.readdirSync(fileURLToPath(fileName)).filter(item => item.endsWith('.js')).map(item => path.join(fileName,item)) //拿到控制器文件夹里面的所有js文件并加工成一个完整的路径
    // console.log(fileNameAll)
    fileNameAll.forEach(async item => {
      let { default : arr } = await import(item)
      // console.log(arr)
      arr.forEach(item => {
        if(item.method === 'get') {
          router.get(item.url,item.fn)
        }
        if(item.method === 'post') {
          router.post(item.url,item.fn)
        }
        if(item.method === 'put') {
          router.put(item.url,item.fn)
        }
        if(item.method === 'delete') {
          router.delete(item.url,item.fn)
        }
      })
      app.use(router.routes())
    })
  }
}